package com.money.mvp_dagger_simple.http.module;

import com.money.mvp_dagger_simple.http.HttpUtil;
import com.money.mvp_dagger_simple.http.converterfactory.MGsonConverterFactory;
import com.money.mvp_dagger_simple.http.service.ApiService;
import com.money.mvp_dagger_simple.model.reqparams.IRequestParams;
import com.money.mvp_dagger_simple.model.reqparams.impl.IRequestParamsImpl;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by Money on 2017/8/25.
 */

@Singleton
@Module
public class HttpModule {

    private static final String BASE_URL = "http://192.168.1.125:8080/Test/";

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(HttpLoggingInterceptor logInterceptor){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(logInterceptor)
//                .addInterceptor(new HeadInterceptor())
                .connectTimeout(1000, TimeUnit.SECONDS)
                .writeTimeout(100, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS)) // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        return okHttpClient;
    }

    @Provides
    @Singleton
    HttpLoggingInterceptor provideHttpLoggingInterceptor(){
        return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(OkHttpClient okHttpClient){
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)
                .addConverterFactory(MGsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit;
    }

    @Provides
    @Singleton
    ApiService provideApiService(Retrofit retrofit){
        return retrofit.create(ApiService.class);

    }

    @Provides
    @Singleton
    HttpUtil provideHttpUtil(Retrofit retrofit, ApiService apiService){
        return new HttpUtil(retrofit, apiService);
    }

    @Provides
    @Singleton
    IRequestParams provideIRequestParams(){
        return new IRequestParamsImpl();
    }
}
